package com.google.code.porntube.snap.analyzer;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Node;

import com.google.code.porntube.snap.core.setting.Analyzer;

public final class Config {

	public static com.google.code.porntube.snap.result.Config analyze(String config) throws Exception {
		config = (new StringBuffer(Analyzer.CONFIG_URL).append(config)).toString();
		com.google.code.porntube.snap.result.Config result = new com.google.code.porntube.snap.result.Config();
		URL url = new URL(config);
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				url.openStream()));
		String line;
		StringBuffer html = new StringBuffer();
		while ((line = reader.readLine()) != null) {
			html.append(line);
			html.append("\r\n");
		}
		reader.close();
		Document document = DocumentHelper.parseText(html.toString()
				.replace("&amp;", "@amp;")
				.replace("&", "&amp;")
				.replace("@amp;", "&amp;")
		);
		Node qualityselectorNode = document.selectSingleNode("/config/qualityselector.streams");
		Node node = qualityselectorNode.selectSingleNode("stream[@label='480p']");
		if(node == null) {
			node = qualityselectorNode.selectSingleNode("stream[@label='360p']");
			if(node == null) {
				node = qualityselectorNode.selectSingleNode("stream[@label='240p']");
			}
		}
		result.setVideo(node.getStringValue());
		Node imageNode = document.selectSingleNode("/config/image");
		result.setThumbnail(imageNode.getText());
		result.setUrl(config);
		return result;
	}

}
